package cn.donave.component.cms.fckeditor;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class ConnectorServlet extends HttpServlet {
	private static final Log log = LogFactory.getLog(ConnectorServlet.class);
	private static String baseDir;

	public void init() throws ServletException {
		baseDir = getInitParameter("baseDir");
		if (baseDir == null)
			baseDir = "/UserFiles/";
		String str = getServletContext().getRealPath(baseDir);
		File localFile = new File(str);
		if (!(localFile.exists()))
			localFile.mkdir();
	}

	public void doGet(HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse)
			throws ServletException, IOException {
		Object localObject1;
		Object localObject2;
		Object localObject3;
		log.debug("--- BEGIN DOGET ---");
		paramHttpServletResponse.setContentType("text/xml; charset=UTF-8");
		paramHttpServletResponse.setHeader("Cache-Control", "no-cache");
		PrintWriter localPrintWriter = paramHttpServletResponse.getWriter();
		String str1 = paramHttpServletRequest.getParameter("Command");
		String str2 = paramHttpServletRequest.getParameter("Type");
		String str3 = paramHttpServletRequest.getParameter("CurrentFolder");
		String str4 = baseDir + str2 + str3;
		String str5 = getServletContext().getRealPath(str4);
		File localFile = new File(str5);
		if (!(localFile.exists()))
			localFile.mkdir();
		Document localDocument = null;
		try {
			DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			localObject1 = localDocumentBuilderFactory.newDocumentBuilder();
			localDocument = ((DocumentBuilder) localObject1).newDocument();
		} catch (ParserConfigurationException localParserConfigurationException) {
			localParserConfigurationException.printStackTrace();
		}
		Node localNode = CreateCommonXml(localDocument, str1, str2, str3,
				paramHttpServletRequest.getContextPath() + str4);
		log.debug("Command = " + str1);
		if (str1.equals("GetFolders")) {
			getFolders(localFile, localNode, localDocument);
		} else if (str1.equals("GetFoldersAndFiles")) {
			getFolders(localFile, localNode, localDocument);
			getFiles(localFile, localNode, localDocument);
		} else if (str1.equals("CreateFolder")) {
			localObject1 = paramHttpServletRequest
					.getParameter("NewFolderName");
			localObject2 = new File(localFile, (String) localObject1);
			localObject3 = "110";
			if (((File) localObject2).exists())
				localObject3 = "101";
			else
				try {
					boolean bool = ((File) localObject2).mkdir();
					if (bool)
						localObject3 = "0";
					else
						localObject3 = "102";
				} catch (SecurityException localSecurityException) {
					localObject3 = "103";
				}
			setCreateFolderResponse((String) localObject3, localNode,
					localDocument);
		}
		localDocument.getDocumentElement().normalize();
		try {
			localObject1 = TransformerFactory.newInstance();
			localObject2 = ((TransformerFactory) localObject1).newTransformer();
			localObject3 = new DOMSource(localDocument);
			StreamResult localStreamResult1 = new StreamResult(localPrintWriter);
			((Transformer) localObject2).transform((Source) localObject3,
					localStreamResult1);
			if (log.isDebugEnabled()) {
				StreamResult localStreamResult2 = new StreamResult(System.out);
				((Transformer) localObject2).transform((Source) localObject3,
						localStreamResult2);
			}
		} catch (Exception localException) {
			localException.printStackTrace();
		}
		localPrintWriter.flush();
		localPrintWriter.close();
	}

	public void doPost(HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse)
			throws ServletException, IOException {
		log.debug("--- BEGIN DOPOST ---");
		paramHttpServletResponse.setContentType("text/html; charset=UTF-8");
		paramHttpServletResponse.setHeader("Cache-Control", "no-cache");
		PrintWriter localPrintWriter = paramHttpServletResponse.getWriter();
		String str1 = paramHttpServletRequest.getParameter("Command");
		String str2 = paramHttpServletRequest.getParameter("Type");
		String str3 = paramHttpServletRequest.getParameter("CurrentFolder");
		String str4 = baseDir + str2 + str3;
		String str5 = getServletContext().getRealPath(str4);
		log.debug(str5);
		String str6 = "0";
		String str7 = "";
		if (!(str1.equals("FileUpload"))) {
			str6 = "203";
		} else {
			DiskFileItemFactory localDiskFileItemFactory = new DiskFileItemFactory();
			localDiskFileItemFactory.setSizeThreshold(1048576);
			localDiskFileItemFactory.setRepository(new File("e:/test"));
			ServletFileUpload localServletFileUpload = new ServletFileUpload(
					localDiskFileItemFactory);
			localServletFileUpload.setHeaderEncoding("utf-8");
			try {
				List localList = localServletFileUpload
						.parseRequest(paramHttpServletRequest);
				HashMap localHashMap = new HashMap();
				Iterator localIterator = localList.iterator();
				while (localIterator.hasNext()) {
					FileItem localFileItem = (FileItem) localIterator.next();
					if (localFileItem.isFormField())
						localHashMap.put(localFileItem.getFieldName(),
								localFileItem.getString());
					else
						localHashMap.put(localFileItem.getFieldName(),
								localFileItem);
				}
				FileItem localFileItem = (FileItem) localHashMap.get("NewFile");
				String str8 = localFileItem.getName();
				str8 = str8.replace('\\', '/');
				String[] arrayOfString = str8.split("/");
				String str9 = arrayOfString[(arrayOfString.length - 1)];
				String str10 = getNameWithoutExtension(str9);
				String str11 = getExtension(str9);
				File localFile = new File(str5, str9);
				for (int i = 1; localFile.exists(); ++i) {
					str7 = str10 + "(" + i + ")" + "." + str11;
					str6 = "201";
					localFile = new File(str5, str7);
				}
				localFileItem.write(localFile);
			} catch (Exception localException) {
				str6 = "203";
			}
		}
		localPrintWriter.println("<script type=\"text/javascript\">");
		localPrintWriter
				.println("window.parent.frames['frmUpload'].OnUploadCompleted("
						+ str6 + ",'" + str7 + "');");
		localPrintWriter.println("</script>");
		localPrintWriter.flush();
		localPrintWriter.close();
		log.debug("--- END DOPOST ---");
	}

	private void setCreateFolderResponse(String paramString, Node paramNode,
			Document paramDocument) {
		Element localElement = paramDocument.createElement("Error");
		localElement.setAttribute("number", paramString);
		paramNode.appendChild(localElement);
	}

	private void getFolders(File paramFile, Node paramNode,
			Document paramDocument) {
		Element localElement1 = paramDocument.createElement("Folders");
		paramNode.appendChild(localElement1);
		File[] arrayOfFile = paramFile.listFiles();
		for (int i = 0; i < arrayOfFile.length; ++i)
			if (arrayOfFile[i].isDirectory()) {
				Element localElement2 = paramDocument.createElement("Folder");
				localElement2.setAttribute("name", arrayOfFile[i].getName());
				localElement1.appendChild(localElement2);
			}
	}

	private void getFiles(File paramFile, Node paramNode, Document paramDocument) {
		Element localElement1 = paramDocument.createElement("Files");
		paramNode.appendChild(localElement1);
		File[] arrayOfFile = paramFile.listFiles();
		for (int i = 0; i < arrayOfFile.length; ++i)
			if (arrayOfFile[i].isFile()) {
				Element localElement2 = paramDocument.createElement("File");
				localElement2.setAttribute("name", arrayOfFile[i].getName());
				localElement2.setAttribute("size", ""
						+ (arrayOfFile[i].length() / 1024L));
				localElement1.appendChild(localElement2);
			}
	}

	private Node CreateCommonXml(Document paramDocument, String paramString1,
			String paramString2, String paramString3, String paramString4) {
		Element localElement1 = paramDocument.createElement("Connector");
		paramDocument.appendChild(localElement1);
		localElement1.setAttribute("command", paramString1);
		localElement1.setAttribute("resourceType", paramString2);
		Element localElement2 = paramDocument.createElement("CurrentFolder");
		localElement2.setAttribute("path", paramString3);
		localElement2.setAttribute("url", paramString4);
		localElement1.appendChild(localElement2);
		return localElement1;
	}

	private static String getNameWithoutExtension(String paramString) {
		return paramString.substring(0, paramString.lastIndexOf("."));
	}

	private String getExtension(String paramString) {
		return paramString.substring(paramString.lastIndexOf(".") + 1);
	}
}